package com.codebox.ourblogs.module;

import android.annotation.SuppressLint;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.LinearLayout;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.codebox.common.base.Resource;
import com.codebox.common.common.Constants;
import com.codebox.common.common.RouterPath;
import com.codebox.common.common.WebActivity;
import com.codebox.common.util.ToastUtils;
import com.codebox.ourblogs.R;
import com.codebox.ourblogs.bean.BlogBean;
import com.codebox.ourblogs.databinding.ActivityBlogsBinding;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Able
 * @date 2018/12/26
 */
@Route(path = RouterPath.BlogRouterPath.PATH_BLOG)
public class BlogsActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener {

    private ActivityBlogsBinding mBinding;
    Drawable drawable;
    private ArrayList<BlogBean> mBlogList;
    private BlogAdapter mBlogAdapter;
    private int mPageNo = 1;
    private BlogViewModel mBlogViewModel;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_blogs);

        initView();
        initListener();
        onRefresh();
    }


    private void initView() {
        mBinding.toolBar.setNavigationIcon(R.drawable.ic_back);
        // 设置显示menu
        setSupportActionBar(mBinding.toolBar);
        getSupportActionBar().setHomeButtonEnabled(true);
        setNavigationOnClickListener();

        mBinding.swipeRefreshLayout.setColorSchemeResources(
                android.R.color.holo_blue_light,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        mBinding.swipeRefreshLayout.setOnRefreshListener(this);

        initAdapter();
        mBlogViewModel = ViewModelProviders.of(BlogsActivity.this).get(BlogViewModel.class);
    }

    private void initAdapter() {
        mBlogList = new ArrayList<>();
        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mBinding.recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayout.VERTICAL));
        mBlogAdapter = new BlogAdapter(R.layout.item_blog, mBlogList);
        mBlogAdapter.setOnLoadMoreListener(this, mBinding.recyclerView);
        mBinding.recyclerView.setAdapter(mBlogAdapter);

        mBlogAdapter.setOnItemClickListener((adapter, view, position) -> {

            BlogBean blogBean = mBlogList.get(position);
            goWebView(blogBean.getTitle(), blogBean.getLink());
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_search, menu);
        return super.onCreateOptionsMenu(menu);
    }

    protected void setNavigationOnClickListener() {
        mBinding.toolBar.setNavigationOnClickListener(v -> onBackPressed());
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initListener() {
        mBinding.etSearch.addTextChangedListener(new MyTextWatcher());

        mBinding.etSearch.setOnTouchListener((v, event) -> {
            drawable = mBinding.etSearch.getCompoundDrawables()[2];
            if (drawable != null && event.getX() > mBinding.etSearch.getWidth()
                    - mBinding.etSearch.getPaddingRight() - drawable.getIntrinsicWidth()) {
                mBinding.etSearch.setText("");
            }
            return false;
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.menu_search) {
            onRefresh();
            ToastUtils.showWarning("menu");
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onRefresh() {
        mPageNo = 1;
        getBlogData(true);
    }

    @Override
    public void onLoadMoreRequested() {
        mPageNo++;
        getBlogData(false);
    }

    private void getBlogData(boolean isRefresh) {

        String keyword = mBinding.etSearch.getText().toString();
        mBlogViewModel
                .searchBlogs(keyword, mPageNo)
                .observe(BlogsActivity.this,
                        listResource -> dealResult(listResource, isRefresh));
    }

    private void dealResult(Resource<List<BlogBean>> listResource, boolean isRefresh) {
        switch (listResource.status) {
            case SUCCESS:
                List<BlogBean> datas = listResource.data;
                if (isRefresh) {
                    mBlogList.clear();
                    if (datas != null) {
                        mBlogList.addAll(datas);
                    }
                    mBlogAdapter.notifyDataSetChanged();
                    mBinding.swipeRefreshLayout.setRefreshing(false);
                } else {
                    if (datas != null) {
                        mBlogList.addAll(datas);
                        mBlogAdapter.loadMoreComplete();
                    } else {
                        mBlogAdapter.loadMoreEnd();
                    }
                }

                break;
            case LOADING:
                break;
            case FAILURE:
                break;
            case ERROR:
                break;
            default:
        }
    }

    private void goWebView(String title, String link) {
        Intent intent = new Intent(this, WebActivity.class);
        intent.putExtra(Constants.EXTRA_WEB_TITLE, title);
        intent.putExtra(Constants.EXTRA_WEB_URL, link);
        startActivity(intent);
    }

    /**
     * EditText监听
     */
    class MyTextWatcher implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (drawable != null) {
                if (s.length() != 0) {
                    drawable.setAlpha(255);
                } else {
                    drawable.setAlpha(0);
                }
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }


}

